﻿namespace S7.Net.Types
{
    using System;

    public static class Int
    {
        public static short CWord(int value)
        {
            if (value > 0x7fff)
            {
                value -= 0x8000;
                value = 0x8000 - value;
                value *= -1;
            }
            return (short) value;
        }

        public static short FromByteArray(byte[] bytes)
        {
            if (bytes.Length != 2)
            {
                throw new ArgumentException("Wrong number of bytes. Bytes array must contain 2 bytes.");
            }
            return (short) (bytes[1] | (bytes[0] << 8));
        }

        public static short[] ToArray(byte[] bytes)
        {
            int num = bytes.Length / 2;
            short[] numArray = new short[num];
            int num2 = 0;
            for (int i = 0; i < num; i++)
            {
                byte[] buffer1 = new byte[] { bytes[num2++], bytes[num2++] };
                numArray[i] = FromByteArray(buffer1);
            }
            return numArray;
        }

        public static byte[] ToByteArray(short value)
        {
            byte[] buffer1 = new byte[2];
            buffer1[1] = (byte) (value & 0xff);
            buffer1[0] = (byte) ((value >> 8) & 0xff);
            return buffer1;
        }

        public static byte[] ToByteArray(short[] value)
        {
            byte[] buffer = new byte[value.Length * 2];
            int num = 0;
            for (int i = 0; i < value.Length; i++)
            {
                buffer[num++] = (byte) (value[i] & 0xff);
                buffer[num++] = (byte) ((value[i] >> 8) & 0xff);
            }
            return buffer;
        }
    }
}

